import pandas as pd
import plotly.express as px
import plotly.graph_objects as go


def create_price_distribution(df, selected_area):
    """创建价格分布直方图"""
    fig = px.histogram(
        df,
        x='price',
        nbins=50,
        title=f'价格分布 - {selected_area}',
        color='neighbourhood_group',
        labels={'price': '价格 (美元)', 'count': '房源数量'},
        opacity=0.8
    )
    fig.update_layout(
        bargap=0.1,
        xaxis_title='价格 (美元)',
        yaxis_title='房源数量',
        legend_title='行政区',
        hovermode='x unified'
    )
    return fig


def create_room_type_distribution(df, selected_area):
    """创建房间类型分布图"""
    room_counts = df['room_type'].value_counts().reset_index()
    room_counts.columns = ['room_type', 'count']

    fig = px.pie(
        room_counts,
        names='room_type',
        values='count',
        title=f'房间类型分布 - {selected_area}',
        hole=0.3,
        color_discrete_sequence=px.colors.sequential.RdBu
    )
    fig.update_traces(
        textposition='inside',
        textinfo='percent+label',
        hoverinfo='label+percent+value'
    )
    fig.update_layout(
        legend_title='房间类型',
        uniformtext_minsize=12,
        uniformtext_mode='hide'
    )
    return fig


def create_nyc_map(df, selected_area):
    """创建纽约房源分布地图"""
    # 抽样处理，避免地图点过多
    if len(df) > 1000:
        df = df.sample(1000, random_state=42)

    fig = px.scatter_mapbox(
        df,
        lat="latitude",
        lon="longitude",
        color="price",
        size="number_of_reviews",
        hover_name="name",
        hover_data=["price", "room_type", "minimum_nights"],
        title=f'纽约Airbnb分布图 - {selected_area}',
        zoom=10,
        color_continuous_scale=px.colors.cyclical.IceFire,
        range_color=[0, 300]
    )
    fig.update_layout(
        mapbox_style="open-street-map",
        margin={"r": 0, "t": 40, "l": 0, "b": 0},
        coloraxis_colorbar=dict(
            title="价格 (美元)",
            thickness=20,
            len=0.5
        )
    )
    return fig


def create_neighborhood_comparison(df):
    """创建行政区价格对比图"""
    avg_price = df.groupby('neighbourhood_group')['price'].mean().reset_index()

    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=avg_price['neighbourhood_group'],
        y=avg_price['price'],
        marker_color=px.colors.qualitative.Pastel,
        text=avg_price['price'].round(2),
        textposition='outside'
    ))

    fig.update_layout(
        title='各行政区平均价格对比',
        xaxis_title='行政区',
        yaxis_title='平均价格 (美元)',
        hovermode='x',
        showlegend=False
    )
    return fig